package com.boot.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONObject;
import com.boot.entity.StuInfo;
import com.boot.entity.TeaInfo;
import com.boot.repository.StuInfoRepository;
import com.boot.repository.TeaInfoRepository;
import com.boot.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.boot.util.StringUtil;
import com.boot.vo.BaseMessage;
import com.boot.vo.MessageHandler;
import com.boot.vo.Token;
import com.boot.vo.TokenHandler;

/**
 * 登录相关
 */
@Controller
@CrossOrigin(origins = "*")

public class LoginController {
    public static final String namerex = "^[A-z\\u4e00-\\u9fa5]*$";
    public static final String REGEX_PASSWORD = "^(?![\\d]+$)(?![a-zA-Z]+$)(?![-_]+$)[\\da-zA-Z-_]{6,32}$";
    Pattern regPassword = Pattern.compile(REGEX_PASSWORD);

    @Autowired
    private StuInfoRepository stuInfoRepository;

    @Autowired
    private TeaInfoRepository teaInfoRepository;


//	@GetMapping({"","/login"})
//	public String login() {
//		return "login";
//	}

//    @ResponseBody
//    @PostMapping("/register")
//    public BaseMessage<String> register(@RequestBody User user) {
//
//        if (StringUtil.isNotBlank(user.getPassword()) && !regPassword.matcher(user.getPassword()).matches()) {
//            return MessageHandler.createFailedVo("密码长度为6-32个字符；\n" +
//                    "字母，数字或者特殊字符（-_）至少包含两种");
//        }
//        if (StringUtil.isNotBlank(user.getName()) && !Pattern.compile(namerex).matcher(user.getName()).matches()) {
//            return MessageHandler.createFailedVo("姓名只能包含中英文");
//        }
//
//        int n = userMapper.insertUser(user);
//        if (n == 1) {
//            return MessageHandler.createSuccessVo("注册成功");
//        }
//        return MessageHandler.createFailedVo("注册失败", 1);
//    }

    @ResponseBody
    @PostMapping("/login")
    public BaseMessage<?> loginP(@RequestBody String str) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(str);
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        if (StringUtil.isBlank(username) || StringUtil.isBlank(password)) {
            return MessageHandler.createFailedVo("用户或密码不能为空！", 1);
        }
        Integer type = jsonObject.getInteger("type");

        Map<String, Object> result = new HashMap<String, Object>();

        // 0 学生 1 老师 3 管理员
        if (type == 0) {
            StuInfo stuInfo = stuInfoRepository.findByStudentNumberAndPassword(username, password);
            if (stuInfo != null) {
                String token = TokenHandler.create(stuInfo.getId(), 0, stuInfo.getName());
                result.put("token", token);
                result.put("username", stuInfo.getName());
//                result.put("type", user.getType());
                result.put("uid", stuInfo.getId());
                result.put("flag", stuInfo.getChangePassword());
                result.put("majorId",stuInfo.getMajorId());
                result.put("schoolId",stuInfo.getSchoolId());
                return MessageHandler.createSuccessVo(result, "登录成功");
            }
        } else if (type == 1) {
            TeaInfo teaInfo = teaInfoRepository.findByWorkNumberAndPassword(username, password);
            if (teaInfo != null) {
                String token = TokenHandler.create(teaInfo.getId(), 0, teaInfo.getName());
                result.put("token", token);
                result.put("username", teaInfo.getName());
//                result.put("type", user.getType());
                result.put("uid", teaInfo.getId());
                result.put("flag", teaInfo.getChangePassword());
                return MessageHandler.createSuccessVo(result, "登录成功");
            }
        } else if (type == 3) {
            if (Constants.DEFAULT_USERNAME.equals(username) && Constants.DEFAULT_PASSWORD.equals(password)) {
                result.put("username", Constants.DEFAULT_USERNAME);
                result.put("flag", true);
                return MessageHandler.createSuccessVo(result, "登录成功");
            }
        }
        return MessageHandler.createFailedVo("用户名或者密码不存在", 1);

    }

    @ResponseBody
    @RequestMapping(value = "/login/checkToken")
    public BaseMessage<?> checkToken() throws Exception {
        Token to = TokenHandler.getBusinesser();
        if (to != null) {
            boolean stu = stuInfoRepository.existsById(to.getBusinessId());
            if (stu) {
                boolean empty = teaInfoRepository.existsById(to.getBusinessId());
                if (empty) {
                    return MessageHandler.createFailedVo("token失败！");
                }
            }
            return MessageHandler.createSuccessVo("token验证成功！");
        }
        return MessageHandler.createFailedVo("token失败！");
    }
}